package com.ruoyi.system.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.redis.service.RedisService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * SmsUtil
 *
 * @ClassName SmsUtil
 * @Author chengxin.ju
 * @Description
 * @Date 2020/03/03 18:14
 **/
@Slf4j
@Service
public class SmsUtil {

    @Autowired
    private RedisService redisUtil;

    @Value("${sms.regionld}")
    private String  regionld;

    @Value("${sms.accessKeyId}")
    private String  accessKeyId;

    @Value("${sms.accessKeySecret}")
    private String  accessKeySecret;

    // 设置鉴权参数，初始化客户端



    public AjaxResult sendVerificationCode(String phone){

        DefaultProfile profile = DefaultProfile.getProfile(
                regionld,// 地域ID
                accessKeyId,// 您的AccessKey ID
                accessKeySecret);// 您的AccessKey Secret
        IAcsClient client = new DefaultAcsClient(profile);

        String code = String.valueOf((int)((Math.random()*9+1)*100000));
        redisUtil.setCacheObject("verificationCode"+phone,code);
        redisUtil.expire("verificationCode"+phone,5,TimeUnit.MINUTES);

        Map<String,String> mapExtras = new HashMap<>(2);
        mapExtras.put("CODE",code);
        CommonRequest request = new CommonRequest();
        request.setSysDomain("dysmsapi.aliyuncs.com");
        request.setSysVersion("2017-05-25");
        request.setSysAction("SendSms");
        // 接收短信的手机号码
        request.putQueryParameter("PhoneNumbers", phone);
        // 短信签名名称。请在控制台签名管理页面签名名称一列查看（必须是已添加、并通过审核的短信签名）。
        request.putQueryParameter("SignName", "全世爱");
        // 短信模板ID
        request.putQueryParameter("TemplateCode", "SMS_184821279");
        // 短信模板变量对应的实际值，JSON格式。
        request.putQueryParameter("TemplateParam", "{\"code\":"+code +"}");
        CommonResponse commonResponse = null;
        try {
            commonResponse = client.getCommonResponse(request);
        } catch (ClientException e) {
            log.error("sendVerificationCode",e);
        }
        String data = commonResponse.getData();
        String sData = data.replaceAll("'\'", "");
        Map map = JSONObject.parseObject(sData, Map.class);
        String retCode = map.get("Code").toString();
        map = new HashMap();
        if("OK".equals(retCode)){
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }
}

